package org.itzheng.itplayer.local

import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.material.tabs.TabLayout
import org.itzheng.base.BaseFragment
import org.itzheng.itplayer.R
import org.itzheng.itplayer.bean.VideoFolder
import org.itzheng.itplayer.bean.VideoInfo
import java.io.File

/**
 * Title:本地视频，包含两种显示方式，一个是文件列表，一个是文件夹<br></br>
 * Description: <br></br>
 * 点击文件列表直接播放
 * 点击文件夹，进入文件夹，接着同文件列表的操作
 *
 * @email ItZheng@ZoHo.com
 * Created by itzheng on 2020-12-4.
 */
class LocalVideoFragment : BaseFragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflate(R.layout.fragment_local_video)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        scanVideo()
        rootView.findViewById<TabLayout>(R.id.tabLayout)
            .addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                override fun onTabSelected(tab: TabLayout.Tab) {
                    showSubFragment(tab.position)
                }

                override fun onTabUnselected(tab: TabLayout.Tab) {}
                override fun onTabReselected(tab: TabLayout.Tab) {}
            })
    }

    /**
     * 所有的视频
     */
    private val mItems = mutableListOf<VideoInfo>()
    private fun scanVideo() {
        val cursor = context!!.contentResolver.query(
            MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null,
            null, null
        )
        if (cursor != null) {
            while (cursor.moveToNext()) {
                val item = VideoInfo()
                item.fId = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID))
                item.fTitle =
                    cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE))
                item.fAlbum =
                    cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.ALBUM))
                item.fArtist =
                    cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.ARTIST))
                item.fDisplayName =
                    cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME))
                item.fMimeType =
                    cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE))
                item.fPath =
                    cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA))
                item.fDuration =
                    cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION))
                        .toLong()
                item.fSize =
                    cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE))
                item.fDate =
                    cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_TAKEN))
                mItems.add(item)
                Log.w(TAG, "fId: ${item.fId}");
            }
            cursor.close()
        }
        initSubFragment()
    }

    private var mSubFragment = mutableListOf<BaseFragment>()

    private fun initSubFragment() {
        if (mSubFragment.isEmpty()) {
            mSubFragment.add(LocalVideoFileFragment.newInstance(mItems))
            //按文件夹分类
            mSubFragment.add(LocalVideoFolderFragment.newInstance(fileClassify(mItems)))
        }
        showSubFragment(0)
    }

    /**
     * 将文件按文件夹名称分类
     */
    private fun fileClassify(items: MutableList<VideoInfo>): ArrayList<VideoFolder> {
        val folders = mutableListOf<VideoFolder>()
        if (items == null || items.isEmpty()) {
            return folders as ArrayList<VideoFolder>;
        }
        var folder: VideoFolder? = null
        for (item in items) {
            val file = File(item.fPath)
            if (folder == null || !(folder?.fName.equals(file.parent))) {
                //路径不同，那么就重新创建
                folder = VideoFolder()
                folder.fName = file.parent
                folder.fContent = mutableListOf()
                folders.add(folder)
            }
            folder.fContent.add(item)
        }
        //将数据添加到文件夹，但是可能出现同一个文件出现多次的情况
        val map = mutableMapOf<String, VideoFolder>()
        for (folder in folders) {
            var old = map.get(folder.fName)
            if (old != null) {
                old.fContent.addAll(folder.fContent)
            } else {
                //之前没数据，那就是这个数据
                old = folder
            }
            map.put(old.fName, old)
        }
        //现在所有的数据都在map里面了
        //这个是过滤后的新的集合，避免map乱序
        val filterFolders = mutableListOf<VideoFolder>();
        for (folder in folders) {
            val data = map.get(folder.fName)
            if (data != null) {
                filterFolders.add(data);
                map.remove(folder.fName)
            }
        }
        return filterFolders as ArrayList<VideoFolder>
    }

    var fragment: BaseFragment? = null

    /**
     * 显示fragment
     *
     */
    private fun showSubFragment(position: Int) {
        if (mSubFragment.size <= position) {
            //数组越界
            return
        }
        val newFragment = mSubFragment[position]
        if (newFragment === fragment) {
            //相当于再次点击，可以进行刷新操作
//                newFragment.refresh()
            return
        }
        if (fragment != null) {
            childFragmentManager.beginTransaction().hide(fragment!!)
                .commitAllowingStateLoss()
        }
        fragment = newFragment
        //判断fragment是否被添加；如果被添加则显示，如果未添加则添加
        if (fragment!!.isAdded()) {
            childFragmentManager.beginTransaction().show(fragment!!)
                .commitAllowingStateLoss()
        } else {
            childFragmentManager.beginTransaction().add(R.id.layoutContent, fragment!!)
                .commitAllowingStateLoss()
        }
    }

    companion object {
        @JvmStatic
        fun newInstance(): LocalVideoFragment {
            val args = Bundle()
            val fragment = LocalVideoFragment()
            fragment.arguments = args
            return fragment
        }
    }
}